#!/usr/bin/env python3
# Created by han on 2016/7/6
import os
import hashlib
import json


def get_file_md5(filename):
    if not os.path.isfile(filename):
        return "no file"
    myhash = hashlib.md5()
    with open(filename, "rb") as file:
        while True:
            b = file.read(8096)
            if not b:
                break
            myhash.update(b)
    return myhash.hexdigest()


def dir_size(path):
    """
    获取目录的大小
    :param path:
    :return:
    """
    a = os.walk(path)
    size = 0
    for root, dirs, files in a:
        size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
    return size


def color_msg(color, text, width, fill=" "):
    """
    格式化，可以定义颜色，文字的位置
    :param color: 文字颜色
    :param text: 文字内容
    :param width: 文字位置
    :param fill: 文字填充 default=" "
    :return:
    """
    msg = "\033[31;{0:d}m {1} \033[33;0m".format(color, text)
    text_msg = msg.center(width, fill)
    print(text_msg)


def send_file(socket_obj, seek_num, abs_filename, client_size, file_size):
    """
    读取文件并且传输给客户端
    :param socket_obj: socket对象
    :param seek_num: 客户端的文件的seek值
    :param abs_filename: 文件绝对路径
    :param client_size: 客户端断点时的文件大小
    :param file_size: 本地文件大小
    :return:
    """
    with open(abs_filename, "rb") as local_file:
        local_file.seek(seek_num)
        send_size = client_size
        for i in local_file:
            socket_obj.request.sendall(i)
            send_size += len(i)
            print("file_size: %s, send_size: %s" % (file_size,send_size))
    if send_size == file_size:
        return True


def read_info(user_name):
    with open("../db/%s" % user_name, "r", encoding="utf8") as userr_file:
        info_json = userr_file.read()
        info_dict = json.loads(info_json)
    return info_dict